﻿using System;
using System.Management;
using System.Diagnostics;

namespace HyperV
{
    public partial class VMHelper
    {
        private static void RequestStateChange(ManagementScope scope, string vmName, string action)
        {
            ManagementObject vm = Utility.GetTargetComputer(vmName, scope);

            if (null == vm)
            {
                throw new ArgumentException(
                    string.Format(
                    "The virtual machine '{0}' could not be found.",
                    vmName));
            }

            ManagementBaseObject inParams = vm.GetMethodParameters("RequestStateChange");

            const int Enabled = 2;
            const int Disabled = 3;

            if (action.ToLower() == "start")
            {
                inParams["RequestedState"] = Enabled;
            }
            else if (action.ToLower() == "stop")
            {
                inParams["RequestedState"] = Disabled;
            }
            else
            {
                throw new Exception("Wrong action is specified");
            }

            ManagementBaseObject outParams = vm.InvokeMethod(
                "RequestStateChange",
                inParams,
                null);

            if ((UInt32)outParams["ReturnValue"] == ReturnCode.Started)
            {
                if (Utility.JobCompleted(outParams, scope))
                {
                    Debug.WriteLine(
                        "{0} state was changed successfully.",
                        vmName);
                }
                else
                {
                    Debug.WriteLine("Failed to change virtual system state");
                }
            }
            else if ((UInt32)outParams["ReturnValue"] == ReturnCode.Completed)
            {
                Debug.WriteLine(
                    "{0} state was changed successfully.",
                    vmName);
            }
            else
            {
                Debug.WriteLine(
                    "Change virtual system state failed with error {0}",
                    outParams["ReturnValue"]);
            }

        }

        public void Start(String vmName)
        {
            RequestStateChange(Scope, vmName, "start");
        }

        public static void Start(ManagementScope scope, String vmName)
        {
            RequestStateChange(scope, vmName, "start");
        }

        public void Stop(String vmName)
        {
            RequestStateChange(Scope, vmName, "stop");
        }

        public static void Stop(ManagementScope scope, String vmName)
        {
            RequestStateChange(scope, vmName, "stop");
        }

    }
}


